/**
 * 主程序
 * email:chiangbt@geoportal.cn
 * 2019-03-20
 */
const express = require('express'); // express包
const cors = require('cors'); // cors跨域包
const path = require('path');
const logger = require('morgan'); // 日志包
const bodyParser = require('body-parser'); // body数据解析包
const mongoose = require('mongoose'); // mongodb连接包
const swaggerUi = require('swagger-ui-express'); // swagger包
const compression = require('compression') // 压缩包
const session = require("express-session");
// 设置express的app对象
const app = express();
// 启动对配置文件.env的读取
require('dotenv').config();

// 连接mongodb数据库
mongoose.connect(process.env.DB_CONN, {
        useCreateIndex: true,
        useNewUrlParser: true
    })
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.log(err))
mongoose.Promise = global.Promise

// 在console中记录日志
app.use(logger('dev'));
// 开启压缩
app.use(compression());
// 让express能够解析读取的json对象
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
// session
app.use(session({
    secret: 'secret',
    resave: false,
    saveUninitialized: true
}))
// 处理CORS跨域情况
// app.use(cors({credentials: true, origin: true}));
app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization"
    );
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
        return res.status(200).json({});
    }
    next();
});

// 添加路由
const productRoutes = require('./src/routes/product');
const orderRoutes = require('./src/routes/order');
const userRoutes = require('./src/routes/user');
const cityRoutes = require('./src/routes/city');
const profileRoutes = require('./src/routes/profile');
app.use('/api', productRoutes);
app.use('/api', orderRoutes);
app.use('/api', userRoutes);
app.use('/api', cityRoutes);
app.use('/api', profileRoutes);

// 配置swagger
const options = require('./src/config/swagger.json');
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(options));

// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname + '/client/build/index.html'));
});

// 处理uri资源不存在的情况
app.use((req, res, next) => {
    const error = new Error('客户端访问的URI并不存在');
    error.status = 404;
    next(error);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    });
});

module.exports = app;